package org.douxiaoban.client.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.douxiaoban.client.R;
import org.douxiaoban.client.api.DouGroupApi;
import org.douxiaoban.client.tab.DouGroupOneTopicTab;
import org.douxiaoban.client.util.DouUtils;
import org.douxiaoban.client.util.Panel;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.util.WorkspaceView.ScrollToScreenCallback;
import org.douxiaoban.client.widget.PageControlerView;
import org.douxiaoban.client.widget.PageControlerView.OnPageChangedListener;
import org.douxiaoban.client.widget.TitleStyle;
import org.douxiaoban.client.widget.TitleStyle.WriteMiniBlog;
import org.douxiaoban.data.DouGroupOneTopicData;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 豆瓣小组单条,话题-
 * 
 * @author 6a209 10:04:02 PM Jun 5, 2012
 */
public class DouGroupOneTopicAct extends BaseActivity {
	private DouGroupOneTopicTab mMainView;
	private DouGroupApi mApi;
	private String mTopicUrl;
	private String mTopicGroupName;
	private String mTopicGroupLink;
	
	private Panel mPanel;
	private EditText mReplyEditText;
	private Button mSendBtn;
	private Button mCancelBtn;
	
	/*评论的页数*/
	private int mReplyPageCount;
	private int mCurPage;
	private WorkspaceView mWorkSpaceView;
	private PageControlerView mPageControler;
	private ArrayList<DouGroupOneTopicTab> mTopicTabList;
	private DouGroupOneTopicData mInitData;
	private Timer mTimer;
	
	private int mReplyStart = 0;
	public static final String URL_KEY = "url_key";
	public static final String GROUP_NAME_KEY = "group_anme";
	public static final String GROUP_LINK = "group_link";
	private TitleStyle mTitle;

	private static final int NET_ERR_MSG = 0x00;
	private static final int REQ_DATA_INIT = 0x01;
	private static final int REQ_DATA_BY_PAGE = 0x03;
	private static final int SENT_REPLY_MSG = 0x02;


	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.dou_group_one_topic);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title);
		Intent intent = getIntent();
		mTopicUrl = intent.getStringExtra(URL_KEY);
		mTopicGroupName = intent.getStringExtra(GROUP_NAME_KEY);
		mTopicGroupLink = intent.getStringExtra(GROUP_LINK);
//		mPageControler = new PageControler(this);
		mPageControler = (PageControlerView)findViewById(R.id.one_topic_page_controler);
		mTitle = new TitleStyle(this);
		mTitle.initTitleStyle();
		mTitle.initPageController(1, 1);
		mTitle.setTitle(mTopicGroupName);
		mApi = DouGroupApi.instance(getApplicationContext());
		mWorkSpaceView = (WorkspaceView)findViewById(R.id.one_topic_main);
		mMainView = new DouGroupOneTopicTab(this);
		mWorkSpaceView.addView(mMainView);
		mReplyEditText = (EditText)findViewById(R.id.panelEdit);
		mSendBtn = (Button)findViewById(R.id.miniblog_ok);
		mCancelBtn = (Button)findViewById(R.id.miniblog_cancel);
		mPanel = (Panel)findViewById(R.id.topPanel);
		mTopicTabList = new ArrayList<DouGroupOneTopicTab>();
		mTopicTabList.add(mMainView);
		mTimer = new Timer();
		initListener();
		mTitle.initWriteMiniblog(new WriteMiniBlog() {
			@Override
			public void writeMiniBlog() {
				mReplyEditText.setHint("回应该话题");
				mReplyEditText.requestFocus();	
				mPanel.setOpen(true, true);	
				
				//开线程显示键盘！
				new Thread(){
					@Override
					public void  run(){
					     Timer timer = new Timer();
					     timer.schedule(new TimerTask() {
				            @Override
				            public void run() {
				                InputMethodManager m = (InputMethodManager)mReplyEditText.getContext().
				                getSystemService(Context.INPUT_METHOD_SERVICE);
				                m.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
				            }
				        },1000);
					}
				}.start();
			}
		});
		
		reqData(0, REQ_DATA_INIT);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mTimer.cancel();
		if(mMainView.getReplysAdapter() != null){
			mMainView.getReplysAdapter().recycleAll();
		}
	}

	private void initListener(){
		mSendBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sentBtnClick();
			}
		});
		
		mCancelBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				cancelBtnClick();
			}
		});
	}
	
	private void initListViewSrcollListener(){
		for(DouGroupOneTopicTab tab : mTopicTabList){
			tab.getListView().setOnScrollListener(new OnScrollListener() {
				
				@Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					if(OnScrollListener.SCROLL_STATE_IDLE == scrollState){
						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								mPageControler.setVisibility(View.GONE);
							}
						}, 1000 * 6);
					}else{
						mPageControler.setVisibility(View.VISIBLE);
					}
				}
				
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					Log.v("----------", "++++++++++++++++++++++++++++++++");
				}
			});
		}
	}
	
	/**
	 * 重置我说,清空输入,收起下拉列表
	 */
	private void cancelBtnClick(){
		//收起键盘
        InputMethodManager m = (InputMethodManager)mReplyEditText.getContext().
        							getSystemService(Context.INPUT_METHOD_SERVICE);
        m.hideSoftInputFromWindow(mReplyEditText.getWindowToken(), 0);
		mPanel.setOpen(false, true);
		mReplyEditText.setText("");
		mReplyEditText.setHint("说点神马吧!!");
	}
	
	private void sentBtnClick(){
		final List<NameValuePair> params = new ArrayList<NameValuePair>();
		BasicNameValuePair pairContetn = new BasicNameValuePair("rv_comment", 
				mReplyEditText.getText().toString());
		BasicNameValuePair pairStart = new BasicNameValuePair("start", "0");
		BasicNameValuePair pairBtn = new BasicNameValuePair("submit_btn", "加上去");
		String ckValue = "";
		CookieStore store = DouUtils.getInstance(this.getApplicationContext()).getCookieUtil().getLoginCookieStore();
		for(Cookie cookie : store.getCookies()){
//			Log.v("the cookie name is ------------", cookie.getName());
			if(cookie.getName().equals("ck")){
				ckValue = cookie.getValue();
			}
		}
		Log.v("the ck value is ", ckValue);
		BasicNameValuePair pairCk = new BasicNameValuePair("ck", ckValue);
		params.add(pairBtn);
		params.add(pairStart);
		params.add(pairContetn);
		params.add(pairCk);
		new Thread(){
			@Override
			public void run(){
				DouGroupOneTopicData data = mApi.replyTopic(mTopicUrl, params);
				Message msg = mHandler.obtainMessage();
				msg.what = SENT_REPLY_MSG;
				msg.obj = data;
				mHandler.sendMessage(msg);
			}
		}.start();
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REQ_DATA_INIT:
				mInitData= (DouGroupOneTopicData) msg.obj;
				if(null == mInitData){
					Toast.makeText(DouGroupOneTopicAct.this, "网络异常", Toast.LENGTH_SHORT).show();
					return;
				}
				mMainView.initView(mInitData);
				mReplyPageCount = mInitData.mReplyPageCount;
				if(mReplyPageCount > 1){
					mPageControler.setVisibility(View.VISIBLE);
					mPageControler.setPageCount(mReplyPageCount);
					mPageControler.setOnPageChangedListener(new OnPageChangedListener() {
						@Override
						public void onPageClick(int page) {
							mWorkSpaceView.scrollToScreen(page);
						}
					});
					for(int i = 0; i < mReplyPageCount - 1; i++){
						DouGroupOneTopicTab oneTopic = new DouGroupOneTopicTab(DouGroupOneTopicAct.this);
						mTopicTabList.add(oneTopic);
						oneTopic.setOnlyTitle();
						mWorkSpaceView.addView(oneTopic);
					}
					//为listView 加滚动监听
					initListViewSrcollListener();
					mWorkSpaceView.setScrollToScreenCallback(new ScrollToScreenCallback() {
						@Override
						public void callback(int currentIndex) {
							if(!mTopicTabList.get(currentIndex).hasData()){
								reqData(currentIndex, REQ_DATA_BY_PAGE);
							}
							mPageControler.updateCurPageStatu(currentIndex);
						}
					});
				}else{
					mPageControler.setVisibility(View.GONE);
				}
				break;
			case REQ_DATA_BY_PAGE:
				DouGroupOneTopicData pageData = (DouGroupOneTopicData)msg.obj;
				DouGroupOneTopicTab tab = mTopicTabList.get(mCurPage);
				Log.v("the cur page is -----" + mCurPage, "----------======------");
//				pageData.mTitle = mInitData.mTitle;
				tab.initView(pageData);
				break;
			case NET_ERR_MSG:
				Toast.makeText(DouGroupOneTopicAct.this, "网络异常",
						Toast.LENGTH_SHORT).show();
				break;
			case SENT_REPLY_MSG:
				DouGroupOneTopicData data = (DouGroupOneTopicData)msg.obj;
				if(null != data && data.mReplys.size() > 0){
					mMainView.initView(data);
					Toast.makeText(DouGroupOneTopicAct.this, "评论成功",
							Toast.LENGTH_SHORT).show();
					cancelBtnClick();
				}else{
					Toast.makeText(DouGroupOneTopicAct.this, "评论失败",
							Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
		}
	};

	private void reqData(final int page, final int what) {
		
		Thread thread = new Thread(){
			@Override
			public void run() {
				int start = page * 100;
				mCurPage = page;
				String url = mTopicUrl + "?start=" + start;
				DouGroupOneTopicData data = mApi
						.getOneTopicData(url, start);
				if (null != data) {
					Message msg = mHandler.obtainMessage();
					msg.what = what;
					msg.obj = data;
					mHandler.sendMessage(msg);
				} else {
					mHandler.sendEmptyMessage(NET_ERR_MSG);
				}
			}
		};
		thread.start();
	}
	
}